package com.shier.shiercodesandbox.template;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import com.shier.shiercodesandbox.model.ExecuteCodeRequest;
import com.shier.shiercodesandbox.model.ExecuteCodeResponse;
import com.shier.shiercodesandbox.model.ExecuteMessage;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Java调用Docker 实现代码沙箱
 *
 * @author Shier 2023/9/1 11:12
 */
@Component
public class JavaDockerCodeSandbox extends JavaCodeSandboxTemplate{

    public static final long TIME_OUT = 12000L;

    // 首次拉取镜像
    public static final Boolean FIRST_INIT = false;

    /**
     * 3、创建容器，上传编译文件
     * @param userCodeFile
     * @param inputList
     * @return
     */

    @Override
    public List<ExecuteMessage> runCode(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

//        DockerClient dockerClient = DockerClientBuilder.getInstance().build();

        DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
        // 初始化连接
        URI uri = null;
        try {
            uri = new URI("tcp://0.0.0.0:2375");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        DockerHttpClient dockerHttpClient = new ApacheDockerHttpClient.Builder()
                .dockerHost(uri)
                .maxConnections(3000)
                .build();
        DockerClient dockerClient = DockerClientBuilder.getInstance(config).withDockerHttpClient(dockerHttpClient).build();




        // 拉取镜像（如果需要）
        String image = "openjdk:8-alpine";
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载拉取镜像中：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }
        }
        System.out.println("镜像拉取完成");

        // 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(32 * 1024 * 1024L);  // 增加为256MB内存
        hostConfig.withCpuCount(1L);  // 增加 CPU 数量
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                .withReadonlyRootfs(true)
                .withNetworkDisabled(true)
                .withHostConfig(hostConfig)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        String containerId = createContainerResponse.getId();
        System.out.println("创建容器id：" + containerId);

        // 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            final boolean[] flag = {true};
            StopWatch stopWatch = new StopWatch();

            // 设置运行命令
            String[] cmdArray = new String[]{"java", "-cp", "/app", "Main"};

            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {""};
            final String[] errorMessage = {null};
            final long[] time = {0L};

            // 获取执行 ID
            String execId = execCreateCmdResponse.getId();

            // 获取输出和错误信息
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + new String(frame.getPayload()));
                    } else if (flag[0]){
                        flag[0] = false;
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + new String(frame.getPayload()));
                    }
                    super.onNext(frame);
                }
            };
            // 将传入的 inputArgs 转为输入流
            // 检查输入是否包含回车符，如果没有，则加上一个回车符
            if (!inputArgs.endsWith("\n")) {
                inputArgs += "\n";  // 添加回车符
            }

            // 将传入的 inputArgs 转为输入流
            byte[] inputBytes = inputArgs.getBytes(StandardCharsets.UTF_8);
            InputStream inputStream = new ByteArrayInputStream(inputBytes);

            // 设置最大执行时间，1分钟
            long maxExecutionTimeMillis = 1 * 15 * 1000; // 1 minute
            long startTime = System.currentTimeMillis();

            // 启动执行命令并监控超时
            Thread executionThread = new Thread(() -> {
                try {
                    stopWatch.start();
                    dockerClient.execStartCmd(execId)
                            .withStdIn(inputStream)  // 将输入数据传递给容器
                            .exec(execStartResultCallback)
                            .awaitCompletion(TIME_OUT, TimeUnit.MINUTES);
                    stopWatch.stop();
                    time[0] = stopWatch.getLastTaskTimeMillis();
                } catch (InterruptedException e) {
                    System.out.println("程序执行过程中发生错误: " + e.getMessage());
                    throw new RuntimeException("程序执行中断: " + e.getMessage(), e);
                } catch (Exception e) {
                    System.out.println("执行过程中发生异常: " + e.getMessage());
                    throw new RuntimeException("程序执行异常: " + e.getMessage(), e);
                }
            });

            executionThread.start();

            // 监控执行时间
            while (executionThread.isAlive()) {
                // 如果超时，强制停止容器
                if (System.currentTimeMillis() - startTime > maxExecutionTimeMillis) {
                    System.out.println("执行超时，强制停止容器");
                    dockerClient.stopContainerCmd(containerId).exec();  // 停止容器
                    break;  // 强制退出循环
                }
                // 可以适当加个睡眠，避免过度占用CPU
                try {
                    Thread.sleep(500); // 睡眠500毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 获取内存信息
            // 获取内存信息，修改为一次性获取
            StatsCmd statsCmd = dockerClient.statsCmd(containerId).withNoStream(true);  // 设置 noStream 为 true

            final long[] maxMemory = {0L};
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    Long usageMemory = statistics.getMemoryStats().getUsage();
                    System.out.println("内存占用: " + usageMemory);
                    maxMemory[0] = Math.max(usageMemory, maxMemory[0]);
                }

                @Override
                public void onStart(Closeable closeable) {}

                @Override
                public void onError(Throwable throwable) {}

                @Override
                public void onComplete() {}

                @Override
                public void close() throws IOException {}
            });        // 等待 stats 获取完成
            // 通过 sleep 等待数据采集完成
            try {
                Thread.sleep(1500); // 等待1秒，确保数据采集完成
            } catch (InterruptedException e) {
                System.out.println("等待内存统计获取过程中被中断: " + e.getMessage());
            }
            statsCmd.exec(statisticsResultCallback);

            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time[0]);
            executeMessage.setMemory(maxMemory[0]);

            executeMessageList.add(executeMessage);
            System.out.println(executeMessageList);
        }

        // 3.6 清理容器资源
        try {
            dockerClient.stopContainerCmd(containerId).exec();  // 停止容器（如果容器还在运行）
            dockerClient.removeContainerCmd(containerId).withForce(true).exec();  // 强制删除容器
            System.out.println("容器已删除");
        } catch (Exception cleanupException) {
            System.out.println("清理容器失败: " + cleanupException.getMessage());
        }

        return executeMessageList;
    }

}
